import time
import json
import threading
from datetime import datetime
from django.conf import settings
from .mongo_models import PendingComment, mongo_connection
from .audit_chain import audit_chain
from .models import OrderRating, CommentAuditLog
import redis

class AuditWorker:
    """AI自主审核任务处理器（支持文本和图片审核，集成七牛云）"""
    
    def __init__(self):
        try:
            self.redis_client = redis.Redis(
                host=settings.REDIS_TASK_CONFIG['host'],
                port=settings.REDIS_TASK_CONFIG['port'],
                db=settings.REDIS_TASK_CONFIG['db'],
                password=settings.REDIS_TASK_CONFIG['password'],
                decode_responses=True
            )
            # 测试Redis连接
            self.redis_client.ping()
            print("✅ Redis连接成功")
        except Exception as e:
            print(f"Redis连接失败: {str(e)}")
            # 使用Django缓存作为备选
            from django.core.cache import cache
            self.redis_client = None
            self.use_cache = True
            print("使用Django缓存作为备选")
        
        self.pending_comment = PendingComment()
        self.running = False
        self.worker_thread = None
    
    def start(self):
        """启动AI审核工作线程"""
        if not self.running:
            self.running = True
            self.worker_thread = threading.Thread(target=self._work_loop)
            self.worker_thread.daemon = True
            self.worker_thread.start()
            print("AI审核工作线程已启动（支持文本和图片审核，集成七牛云）")
    
    def stop(self):
        """停止AI审核工作线程"""
        self.running = False
        if self.worker_thread:
            self.worker_thread.join()
            print("AI审核工作线程已停止")
    
    def _work_loop(self):
        """AI审核工作循环 - 每分钟执行一次"""
        print("AI审核工作器已启动，每分钟执行一次审核任务")
        
        while self.running:
            try:
                print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - 开始执行审核任务...")
                
                # 获取待审核的评论
                pending_comments = self.pending_comment.get_pending_comments(limit=10)
                
                if pending_comments:
                    print(f"发现 {len(pending_comments)} 个待审核评论")
                    
                    for comment in pending_comments:
                        if comment.get('audit_status') == 0:  # 待审核
                            task = {
                                'comment_id': str(comment['_id']),
                                'text': comment.get('comment', ''),
                                'image_url': comment.get('image_url')
                            }
                            print(f"正在审核评论: {comment.get('comment', '')[:20]}...")
                            self._process_ai_audit_task(task)
                else:
                    print("暂无待审核评论")
                
                # 每分钟执行一次
                print("等待60秒后执行下一次审核...")
                time.sleep(60)
                        
            except Exception as e:
                print(f"AI审核工作线程异常: {str(e)}")
                time.sleep(60)  # 异常后也等待60秒
    
    def _process_ai_audit_task(self, task):
        """处理AI自主审核任务（文本+图片，支持七牛云）"""
        try:
            comment_id = task['comment_id']
            text = task['text']
            image_url = task.get('image_url')  # 从七牛云URL获取图片
            
            print(f"开始AI自主审核任务: {comment_id}")
            print(f"文本内容: {text[:50]}...")
            print(f"图片URL: {image_url if image_url else '无图片'}")
            
            # 获取MongoDB中的评论数据
            comment_data = self.pending_comment.get_comment_by_id(comment_id)
            if not comment_data:
                print(f"评论数据不存在: {comment_id}")
                return
            
            # 执行文本审核
            text_audit_result = audit_chain.audit_text(text)
            print(f"文本审核结果: {text_audit_result['audit_decision']}")
            
            # 执行图片审核（如果有图片URL）
            image_audit_result = None
            if image_url:
                try:
                    image_audit_result = audit_chain.audit_image(image_url)
                    print(f"图片审核结果: {image_audit_result['audit_decision']}")
                except Exception as e:
                    print(f"图片审核失败: {str(e)}")
                    image_audit_result = {
                        'is_sensitive': False,
                        'reason': f'图片审核失败: {str(e)}',
                        'audit_decision': 'pass'
                    }
            
            # 综合判断审核结果
            final_decision = self._combine_audit_results(text_audit_result, image_audit_result)
            audit_status = 1 if final_decision == 'pass' else 2  # 1-通过，2-拒绝
            
            # 生成综合审核结果
            combined_result = self._generate_combined_result(text_audit_result, image_audit_result)
            
            # 更新MongoDB中的审核状态
            self.pending_comment.update_audit_status(
                comment_id=comment_id,
                audit_status=audit_status,
                audit_result=f"AI自主审核: {combined_result['reason']}",
                sensitive_words=','.join(combined_result.get('sensitive_words', []))
            )
            
            # 记录AI审核日志到MySQL
            self._save_ai_audit_log(comment_data, combined_result)
            
            # 只有AI审核通过，才同步到MySQL的OrderRating表
            if audit_status == 1:
                self._sync_to_mysql(comment_data, combined_result)
                print(f"✅ AI审核通过，评论已存入MySQL: {comment_id}")
            else:
                print(f"❌ AI审核不通过，评论已驳回: {comment_id}")
                # 审核不通过，不存入MySQL，前端不会显示
            
            # 将AI审核结果存储到Redis
            if hasattr(self, 'redis_client') and self.redis_client:
                result_key = f"audit_result:{comment_id}"
                self.redis_client.setex(
                    result_key,
                    3600,  # 1小时过期
                    json.dumps(combined_result)
                )
            
            print(f"AI自主审核完成: {comment_id}, 最终决策: {final_decision}, 状态: {audit_status}")
            
        except Exception as e:
            print(f"处理AI审核任务失败: {str(e)}")
    
    def _combine_audit_results(self, text_result, image_result):
        """综合文本和图片审核结果"""
        # 如果文本审核拒绝，直接拒绝
        if text_result.get('audit_decision') == 'reject':
            return 'reject'
        
        # 如果图片审核拒绝，直接拒绝
        if image_result and image_result.get('audit_decision') == 'reject':
            return 'reject'
        
        # 如果文本和图片都通过，则通过
        if text_result.get('audit_decision') == 'pass':
            if not image_result or image_result.get('audit_decision') == 'pass':
                return 'pass'
        
        # 默认通过
        return 'pass'
    
    def _generate_combined_result(self, text_result, image_result):
        """生成综合审核结果"""
        combined_result = {
            'is_sensitive': False,
            'sensitive_words': [],
            'reason': '',
            'suggestion': '通过',
            'confidence': 0.9,
            'audit_decision': 'pass',
            'text_audit': text_result,
            'image_audit': image_result
        }
        
        # 合并敏感词
        if text_result.get('sensitive_words'):
            combined_result['sensitive_words'].extend(text_result['sensitive_words'])
        if image_result and image_result.get('sensitive_words'):
            combined_result['sensitive_words'].extend(image_result['sensitive_words'])
        
        # 生成综合原因
        reasons = []
        if text_result.get('reason'):
            reasons.append(f"文本审核: {text_result['reason']}")
        if image_result and image_result.get('reason'):
            reasons.append(f"图片审核: {image_result['reason']}")
        
        combined_result['reason'] = '; '.join(reasons) if reasons else 'AI自主审核通过'
        
        # 确定最终决策
        final_decision = self._combine_audit_results(text_result, image_result)
        combined_result['audit_decision'] = final_decision
        combined_result['is_sensitive'] = final_decision == 'reject'
        combined_result['suggestion'] = '通过' if final_decision == 'pass' else '拒绝'
        
        # 计算综合置信度
        text_confidence = text_result.get('confidence', 0.8)
        image_confidence = image_result.get('confidence', 0.8) if image_result else 1.0
        combined_result['confidence'] = (text_confidence + image_confidence) / 2
        
        return combined_result
    
    def _save_ai_audit_log(self, comment_data, audit_result):
        """保存AI审核日志到MySQL"""
        try:
            CommentAuditLog.objects.create(
                comment_id=comment_data['_id'],
                order_id=comment_data['order_id'],
                passenger_id=comment_data['passenger_id'],
                driver_id=comment_data['driver_id'],
                original_comment=comment_data['comment'],
                audit_status=1 if audit_result.get('audit_decision') == 'pass' else 2,
                audit_result=f"AI自主审核: {audit_result['reason']}",
                sensitive_words=','.join(audit_result.get('sensitive_words', [])),
                audit_method=f"ai_{audit_result.get('method', 'unknown')}",
                processing_time=audit_result.get('processing_time', 0)
            )
        except Exception as e:
            print(f"保存AI审核日志失败: {str(e)}")
    
    def _sync_to_mysql(self, comment_data, audit_result):
        """将AI审核通过的评论同步到MySQL"""
        try:
            # 检查是否已存在该订单的评价
            existing_rating = OrderRating.objects.filter(
                order_id=comment_data['order_id']
            ).first()
            
            if existing_rating:
                # 更新现有评价
                existing_rating.comment = comment_data['comment']
                existing_rating.rating = comment_data['rating']
                existing_rating.image_url = comment_data.get('image_url')  # 同步图片URL
                existing_rating.audit_status = 1  # AI审核通过
                existing_rating.audit_time = datetime.now()
                existing_rating.audit_result = f"AI自主审核: {audit_result['reason']}"
                existing_rating.is_sensitive = audit_result['is_sensitive']
                existing_rating.save()
            else:
                # 创建新评价
                OrderRating.objects.create(
                    order_id=comment_data['order_id'],
                    passenger_id=comment_data['passenger_id'],
                    driver_id=comment_data['driver_id'],
                    rating=comment_data['rating'],
                    comment=comment_data['comment'],
                    image_url=comment_data.get('image_url'),  # 保存图片URL
                    audit_status=1,  # AI审核通过
                    audit_time=datetime.now(),
                    audit_result=f"AI自主审核: {audit_result['reason']}",
                    is_sensitive=audit_result['is_sensitive']
                )
            
            print(f"AI审核通过的评论已同步到MySQL: {comment_data['_id']}")
            
        except Exception as e:
            print(f"同步AI审核评论到MySQL失败: {str(e)}")
    
    def get_pending_count(self):
        """获取待AI审核任务数量"""
        try:
            if hasattr(self, 'redis_client') and self.redis_client:
                return self.redis_client.llen(settings.REDIS_TASK_CONFIG['task_queue'])
            else:
                # 使用MongoDB直接查询待审核数量
                return len(self.pending_comment.get_pending_comments())
        except Exception as e:
            print(f"获取待AI审核任务数量失败: {str(e)}")
            return 0
    
    def clear_queue(self):
        """清空AI审核任务队列"""
        try:
            if hasattr(self, 'redis_client') and self.redis_client:
                self.redis_client.delete(settings.REDIS_TASK_CONFIG['task_queue'])
            print("AI审核任务队列已清空")
        except Exception as e:
            print(f"清空AI审核任务队列失败: {str(e)}")

# 全局AI审核工作器实例
audit_worker = AuditWorker()

def start_audit_worker():
    """启动AI审核工作器"""
    audit_worker.start()

def stop_audit_worker():
    """停止AI审核工作器"""
    audit_worker.stop() 